package cn.wanho.config.filter;

import cn.wanho.dto.ExamMenuRole;
import cn.wanho.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @Author: heyang
 * @Description: 元数据
 * @Date Create in 2022/8/6 15:46
 */
@Component
public class CustomizeFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Autowired
    UserService userService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求地址，注意这边这个地址如果涉及传入参数，也是被获得到的
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        System.out.println(requestUrl);
        //test?a
        int inx = requestUrl.indexOf("?");
        String url = null;
        if (inx == -1) {
            url = requestUrl;
        } else {
            url = requestUrl.substring(0, inx);
        }
        System.out.println("数据库请求路径"+url);
        //查询具体某个接口的权限，查询本地数据库来获得权限
        List<ExamMenuRole> permissionList = userService.selectListByPath(url);
        // url = /delUser   permissionList={ id=3 ,permissionCode = delete_user, permissionName = 删除用户}
        if (permissionList == null || permissionList.size() == 0) {
            //请求路径没有配置权限，表明该请求接口可以任意访问
            return null;
        }
        String[] attributes = new String[permissionList.size()];
        for (int i = 0; i < permissionList.size(); i++) {
            attributes[i] = permissionList.get(i).getRolePath();
        }
        // attributes = /delUser
        List<ConfigAttribute> list = SecurityConfig.createList(attributes);
        System.out.println(list);
        return list;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
